package manager

import (
	"kyland.com/eagle/lib/localhost"
	"kyland.com/eagle/lib/node"
	serf "kyland.com/eagle/lib/serf"
)

type NodeRes struct {
	Test   string `json:"test"`
	Status struct {
		Code string `json:"code"`
		Msg  string `json:"msg"`
	} `json:"status"`
}

func GetNodes() []*node.Node {
	nodes := make([]*node.Node, 0)
	client, err := serf.New()
	if err != nil {
		mem := &node.Node{
			Name:   localhost.HostName(),
			Addr:   localhost.HostIp(),
			Status: node.NODE_ALIVE,
		}
		return []*node.Node{mem}
	}
	mems := client.GetMembers()
	for _, mem := range mems {
		nodes = append(nodes, &node.Node{
			Name:   mem.Name,
			Addr:   mem.Addr.String(),
			Status: mem.Status,
		})
	}

	return nodes
}

// CheckNodeHealthy check the node whether is healthy
func CheckNodeHealthy(addr string) bool {
	nodes := GetNodes()
	for _, n := range nodes {
		if addr == n.Addr && n.Status == node.NODE_ALIVE {
			return true
		}
	}
	return false
}

func GetHealthyNodes() []string {
	Mutex.Lock()
	defer Mutex.Unlock()
	nodes := []string{}
	for key, value := range node.NodesMap {
		if value == node.NodeAlive {
			nodes = append(nodes, key)
		}
	}

	return nodes
}
